package cn.baddonkey.photography.agent.config.security;

import cn.baddonkey.photography.agent.entity.dto.LoginUser;
import cn.baddonkey.photography.agent.core.enums.YesNoEnum;
import cn.baddonkey.photography.agent.entity.UserInfo;
import cn.baddonkey.photography.agent.service.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfo userInfo = userService.selectUserByUserName(username);
        if (userInfo == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new RuntimeException("登录用户：" + username + " 不存在");
        } else if (userInfo.getDeleted()) {
            log.info("登录用户：{} 已被删除.", username);
            throw new RuntimeException("对不起，您的账号：" + username + " 已被删除");
        } else if (YesNoEnum.YES.toString().equals(userInfo.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new RuntimeException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(userInfo);
    }

    public UserDetails createLoginUser(UserInfo user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setPwd(user.getPassword());
        loginUser.setUserName(user.getUserName());
        loginUser.setNickName(user.getNickName());
        return loginUser;
    }
}
